package com.efun.center.http.config;

import com.efun.center.config.EfunConfiguration;
import org.apache.commons.io.FileUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ProjectConfigBuilder {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 方法映射
     */
    protected Map<String, MethodMapper> methodMappers = new HashMap<String, MethodMapper>();

    /**
     * 获取方法映射
     *
     * @param key
     * @return
     */
    public MethodMapper getMethodMapper(String key) {
        return methodMappers.get(key);
    }

    /**
     * 加载
     *
     * @throws Exception
     */
    public void load() throws Exception {
        logger.info("Begin to load config xml");

        methodMappers.clear();

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        Resource dtdResource = resolver.getResource("project.dtd");
        String dtdFilePath = System.getProperty("java.io.tmpdir") + "/" + dtdResource.getFilename();
        FileUtils.copyInputStreamToFile(dtdResource.getInputStream(), new File(dtdFilePath));

        Resource[] resources = resolver.getResources("*-http.xml");
        for (Resource resource : resources) {
            logger.info("load config " + resource.getFilename());
            InputStream stream = resource.getInputStream();
            String targetFilePath = System.getProperty("java.io.tmpdir") + "/" + resource.getFilename();
            FileUtils.copyInputStreamToFile(stream, new File(targetFilePath));
            parseXml(new File(targetFilePath));
        }

        logger.info("End load config xml");
    }

    @SuppressWarnings("unchecked")
	private void parseXml(File configFile) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(configFile);
        Element project = document.getRootElement();
        String projectEmail = project.attributeValue("email");

        Map<String, String> areaUrl = new HashMap<String, String>();
        List<Element> childElements = project.elements();
        for (Element child : childElements) {
            if (child.getName().equalsIgnoreCase("area")) {
                if (!StringUtils.isEmpty(child.attributeValue("id")) && !StringUtils.isEmpty(child.attributeValue("url"))) {
                    String domainUrl = child.attributeValue("url");
                    String profile = EfunConfiguration.httpProfile;
                    if (!StringUtils.isEmpty(profile) && profile.equalsIgnoreCase("dev")
                            && !StringUtils.isEmpty(child.attributeValue("testUrl"))) {
                        domainUrl = child.attributeValue("testUrl");
                    }
                    areaUrl.put(child.attributeValue("id"), domainUrl);
                }
            } else if (child.getName().equalsIgnoreCase("method")) {
                MethodMapper mapper = new MethodMapper();
                if (!StringUtils.isEmpty(child.attributeValue("id")) && !StringUtils.isEmpty(child.attributeValue("url"))) {
                    mapper.setAreaUrl(areaUrl);
                    mapper.setId(child.attributeValue("id"));
                    mapper.setUrl(child.attributeValue("url"));
                    mapper.setProjectId(project.attributeValue("id"));

                    if (StringUtils.isEmpty(child.attributeValue("email"))) {
                        if (!StringUtils.isEmpty(projectEmail)) {
                            mapper.setEmail(projectEmail);
                        }
                    } else {
                        mapper.setEmail(child.attributeValue("email"));
                    }
                }
                String key = project.attributeValue("id") + "." + mapper.getId();
                methodMappers.put(key, mapper);
                logger.info("load method " + key);
            }
        }
    }

}
